/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.mapper.SysUserMapper;
import com.pig4cloud.pig.admin.service.AppService;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.demo.dto.XlmUserInfo;
import com.pig4cloud.pig.demo.feign.RemoteXlmUserService;
import io.springboot.sms.core.SmsClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lengleng
 * @date 2018/11/14
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppServiceImpl implements AppService {
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	private final RedisTemplate redisTemplate;

	private final SysUserMapper userMapper;

	private final RemoteXlmUserService remoteXlmUserService;

	private final SmsClient smsClient;

	public static String getPsw(int len) {
		// 1、定义基本字符串baseStr和出参password
		String password = null;
		String baseStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+{}|<>?";
		boolean flag = false;
		// 2、使用循环来判断是否是正确的密码
		while (!flag) {
			// 密码重置
			password = "";
			// 个数计数
			int a = 0, b = 0, c = 0, d = 0;
			for (int i = 0; i < len; i++) {
				int rand = (int) (Math.random() * baseStr.length());
				password += baseStr.charAt(rand);
				if (0 <= rand && rand <= 9) {
					a++;
				}
				if (10 <= rand && rand <= 35) {
					b++;
				}
				if (36 <= rand && rand <= 61) {
					c++;
				}
				if (62 <= rand && rand < baseStr.length()) {
					d++;
				}
			}
			// 3、判断是否是正确的密码（4类中仅一类为0，其他不为0）
			flag = (a * b * c != 0 && d == 0) || (a * b * d != 0 && c == 0) || (a * c * d != 0 && b == 0) || (b * c * d != 0 && a == 0);
		}
		return password;
	}

	/**
	 * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
	 *
	 * @param phone 手机号
	 * @return code
	 */
	@Override
	public R<Boolean> sendSmsCode(String phone) {
		List<SysUser> userList = userMapper.selectList(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, phone));

		if (CollUtil.isEmpty(userList)) {
			log.info("手机号未注册:{}", phone);
			SysUser sysUser = new SysUser();
			sysUser.setUsername(String.valueOf(phone));
			sysUser.setPhone(phone);
			sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
			sysUser.setPassword(ENCODER.encode(this.getPsw(6)));
//			userDto.getRole().stream().map(roleId -> {
//				userRole.setRoleId(roleId);
//				SysUserRole userRole = new SysUserRole();
//				userRole.setUserId(sysUser.getUserId());
//				return userRole;
//			}).forEach(sysUserRoleMapper::insert);
			userMapper.insert(sysUser);
			XlmUserInfo info = new XlmUserInfo();
			info.setUserid(sysUser.getUserId());
			R<Boolean> byId = remoteXlmUserService.save(info, SecurityConstants.FROM_IN);
//			return R.ok(Boolean.FALSE, "手机号未注册");
		}

		Object codeObj = redisTemplate.opsForValue().get(CacheConstants.DEFAULT_CODE_KEY + phone);

		if (codeObj != null) {
			log.info("手机号验证码未过期:{}，{}", phone, codeObj);
			return R.ok(Boolean.FALSE, "验证码发送过频繁");
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		log.info("手机号生成验证码成功:{},{}", phone, code);
		redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + phone, code, SecurityConstants.CODE_TIME,
				TimeUnit.SECONDS);

		// 调用短信通道发送
		this.smsClient.sendCode(code, phone);
		return R.ok(Boolean.TRUE);
	}

}
